package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.weiqiao.mall.domain.AccountDetailEntity;
import com.weiqiao.mall.repository.IAccountDetaiRepository;
import com.weiqiao.mall.service.IAccountDetailService;
import com.weiqiao.utils.DateUtil;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("AccountDetailServiceImpl")
public class AccountDetailServiceImpl implements IAccountDetailService {

    @Autowired
    private IAccountDetaiRepository accountDetaiRepository;

    @Override
    public AccountDetailEntity findOneAccountDetail(int company_id, Bson filter) {
        String accountDetailStr = accountDetaiRepository.findOneAccountDetail(company_id, filter);
        if (!StringUtil.isBlank(accountDetailStr)) {
            return new Gson().fromJson(accountDetailStr, AccountDetailEntity.class);
        }
        return null;
    }

    @Override
    public boolean updateDetail(Document doc, Bson filter, int company_id) {
        return accountDetaiRepository.updateDetail(doc, filter, company_id);
    }

    @Override
    public int countNum(int company_id, Bson delete_flag) {
        return accountDetaiRepository.countNum(company_id, delete_flag);
    }

    @Override
    public List<AccountDetailEntity> queryAccountDetail(Bson filter, int company_id, Bson sort, int pageNo, int pageSize) {
        int skip = pageNo * pageSize;
        List<String> detailStrs = accountDetaiRepository.getAccountDetailByFilterSortLimit(company_id, filter, sort, skip, pageSize);
        List<AccountDetailEntity> accountDetailEntityList = new ArrayList<>();
        if (detailStrs != null && detailStrs.size() > 0) {
            for (String detailStr : detailStrs) {
                AccountDetailEntity entity = new Gson().fromJson(detailStr, AccountDetailEntity.class);
                if (StringUtil.isLong(entity.getDeal_time())) {
                    entity.setDeal_time(DateUtil.timestampToString(entity.getDeal_time()));
                }
                if (StringUtil.isLong(entity.getCreat_time())) {
                    entity.setCreat_time(DateUtil.timestampToString(entity.getCreat_time()));
                }
                entity.setNickname(entity.getName());
                accountDetailEntityList.add(entity);
            }
        }
        return accountDetailEntityList;
    }
}
